package com.wm.machine.baselibrary.utils.zxing.encodetype;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.zxing.BarcodeFormat;
import com.wm.machine.baselibrary.R;
import com.wm.machine.baselibrary.utils.zxing.clipboard.ClipboardInterface;
import com.wm.machine.baselibrary.utils.zxing.decode.Intents;
import com.wm.machine.baselibrary.utils.zxing.utils.Contents;


/**
 * Author：     cxp
 * CreatTime：  2017/8/29
 * ContactInfo：
 * Description: 根据不同方式生成不同的二维码
 */

public class EndcodeTypeActivity extends Activity implements View.OnClickListener {
    private static final String TAG = EndcodeTypeActivity.class.getSimpleName();
    private static final int PICK_BOOKMARK = 0;
    private static final int PICK_CONTACT = 1;
    private static final int PICK_APP = 2;
    private Button mBtnApp, mBtnBookMark, mBtnContant, mBtnClipboard, mBtnDefine;
    private EditText mEtContent;


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PICK_BOOKMARK:
                case PICK_APP:
                    showTextAsBarcode(intent.getStringExtra("url")); // Browser.BookmarkColumns.URL
                    break;
                case PICK_CONTACT:
                    // Data field is content://contacts/people/984
                    showContactAsBarcode(intent.getData());
                    break;
            }
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        initView();
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mBtnClipboard.setEnabled(ClipboardInterface.hasText(this));
    }


    private void initView() {
        setContentView(R.layout.activity_encode_type);
        mBtnApp = (Button) findViewById(R.id.share_app_button);
        mBtnBookMark = (Button) findViewById(R.id.share_bookmark_button);
        if (Build.VERSION.SDK_INT >= 23) { // Marshmallow / 6.0
            // Can't access bookmarks in 6.0+
            mBtnBookMark.setEnabled(false);
        } else {
            mBtnBookMark.setEnabled(true);
        }
        mBtnContant = (Button) findViewById(R.id.share_contact_button);
        mBtnClipboard = (Button) findViewById(R.id.share_clipboard_button);
        mEtContent = (EditText) findViewById(R.id.share_text_view);
        mBtnDefine = (Button) findViewById(R.id.share_define_button);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.share_app_button) {
            Intent appIntent = new Intent(Intent.ACTION_PICK);
            appIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            appIntent.setClassName(EndcodeTypeActivity.this, AppPickerActivity.class.getName());
            startActivityForResult(appIntent, PICK_APP);

        } else if (i == R.id.share_bookmark_button) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            intent.setClassName(EndcodeTypeActivity.this, BookmarkPickerActivity.class.getName());
            startActivityForResult(intent, PICK_BOOKMARK);

        } else if (i == R.id.share_contact_button) {
            Intent contentIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            contentIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            startActivityForResult(contentIntent, PICK_CONTACT);

        } else if (i == R.id.share_clipboard_button) {
            CharSequence text = ClipboardInterface.getText(EndcodeTypeActivity.this);
            if (text != null) {
                launchSearch(text.toString());
            }

        } else if (i == R.id.share_define_button) {
            String content = mEtContent.getText().toString();
            if (content != null && !content.isEmpty()) {
                launchSearch(content);
            }

        } else {
        }
    }

    private void launchSearch(String text) {
        Intent intent = new Intent(Intents.Encode.ACTION);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        intent.putExtra(Intents.Encode.TYPE, Contents.Type.TEXT);
        intent.putExtra(Intents.Encode.DATA, text);
        intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString());
        startActivity(intent);
    }

    private void showTextAsBarcode(String text) {
        Log.i(TAG, "Showing text as barcode: " + text);
        if (text == null) {
            return; // Show error?
        }
        Intent intent = new Intent(Intents.Encode.ACTION);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        intent.putExtra(Intents.Encode.TYPE, Contents.Type.TEXT);
        intent.putExtra(Intents.Encode.DATA, text);
        intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString());
        startActivity(intent);
    }

    /**
     * Takes a contact Uri and does the necessary database lookups to retrieve that person's info,
     * then sends an Encode intent to render it as a QR Code.
     *
     * @param contactUri A Uri of the form content://contacts/people/17
     */
    private void showContactAsBarcode(Uri contactUri) {
        Log.i(TAG, "Showing contact URI as barcode: " + contactUri);
        if (contactUri == null) {
            return; // Show error?
        }
        ContentResolver resolver = getContentResolver();

        Cursor cursor;
        try {
            // We're seeing about six reports a week of this exception although I don't understand why.
            cursor = resolver.query(contactUri, null, null, null, null);
        } catch (IllegalArgumentException ignored) {
            return;
        }
        if (cursor == null) {
            return;
        }

        String id;
        String name;
        boolean hasPhone;
        try {
            if (!cursor.moveToFirst()) {
                return;
            }

            id = cursor.getString(cursor.getColumnIndex(BaseColumns._ID));
            name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            hasPhone = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0;

        } finally {
            cursor.close();
        }

        // Don't require a name to be present, this contact might be just a phone number.
        Bundle bundle = new Bundle();
        if (name != null && !name.isEmpty()) {
            bundle.putString(ContactsContract.Intents.Insert.NAME, massageContactData(name));
        }

        if (hasPhone) {
            Cursor phonesCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + '=' + id, null, null);
            if (phonesCursor != null) {
                try {
                    int foundPhone = 0;
                    int phonesNumberColumn = phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    int phoneTypeColumn = phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
                    while (phonesCursor.moveToNext() && foundPhone < Contents.PHONE_KEYS.length) {
                        String number = phonesCursor.getString(phonesNumberColumn);
                        if (number != null && !number.isEmpty()) {
                            bundle.putString(Contents.PHONE_KEYS[foundPhone], massageContactData(number));
                        }
                        int type = phonesCursor.getInt(phoneTypeColumn);
                        bundle.putInt(Contents.PHONE_TYPE_KEYS[foundPhone], type);
                        foundPhone++;
                    }
                } finally {
                    phonesCursor.close();
                }
            }
        }

        Cursor methodsCursor = resolver.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
                null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + '=' + id, null, null);
        if (methodsCursor != null) {
            try {
                if (methodsCursor.moveToNext()) {
                    String data = methodsCursor.getString(
                            methodsCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
                    if (data != null && !data.isEmpty()) {
                        bundle.putString(ContactsContract.Intents.Insert.POSTAL, massageContactData(data));
                    }
                }
            } finally {
                methodsCursor.close();
            }
        }

        Cursor emailCursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + '=' + id, null, null);
        if (emailCursor != null) {
            try {
                int foundEmail = 0;
                int emailColumn = emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
                while (emailCursor.moveToNext() && foundEmail < Contents.EMAIL_KEYS.length) {
                    String email = emailCursor.getString(emailColumn);
                    if (email != null && !email.isEmpty()) {
                        bundle.putString(Contents.EMAIL_KEYS[foundEmail], massageContactData(email));
                    }
                    foundEmail++;
                }
            } finally {
                emailCursor.close();
            }
        }

        Intent intent = new Intent(Intents.Encode.ACTION);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        intent.putExtra(Intents.Encode.TYPE, Contents.Type.CONTACT);
        intent.putExtra(Intents.Encode.DATA, bundle);
        intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString());

        Log.i(TAG, "Sending bundle for encoding: " + bundle);
        startActivity(intent);
    }

    private static String massageContactData(String data) {
        // For now -- make sure we don't put newlines in shared contact data. It messes up
        // any known encoding of contact data. Replace with space.
        if (data.indexOf('\n') >= 0) {
            data = data.replace("\n", " ");
        }
        if (data.indexOf('\r') >= 0) {
            data = data.replace("\r", " ");
        }
        return data;
    }

    private void initListener() {
        mBtnApp.setOnClickListener(this);
        mBtnBookMark.setOnClickListener(this);
        mBtnContant.setOnClickListener(this);
        mBtnClipboard.setOnClickListener(this);
        mBtnDefine.setOnClickListener(this);
    }
}
